package com.ourhours.message.rpc.service.impl;

import com.alibaba.fastjson.JSON;
import com.ourhours.global.response.ApiResponse;
import com.ourhours.global.response.ApiResponseBuilder;
import com.ourhours.message.constant.ConstantMQ;
import com.ourhours.message.api.AppPushRpcService;
import com.ourhours.message.domain.AppPush;
import com.ourhours.message.domain.Supplier;
import com.ourhours.message.dto.PushResponse;
import com.ourhours.message.enums.ApiResponseCode;
import com.ourhours.message.enums.MessageTypeEnum;
import com.ourhours.message.exception.MessageException;
import com.ourhours.message.request.AppPushRequest;
import com.ourhours.message.response.MmsBaseResponseCode;
import com.ourhours.message.service.AppPushService;
import com.ourhours.message.service.SmsSendService;
import com.ourhours.message.service.wrapper.SmsWrapper;
import com.ourhours.message.service.wrapper.SupplierWrapper;
import com.ourhours.redismq.Message;
import com.ourhours.redismq.RedisMQMessageSender;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.JmsException;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.jms.Destination;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service("appPushRpcService")
@Slf4j
public class AppPushRpcServiceImpl implements AppPushRpcService {

    @Autowired
    SmsWrapper messageWrapper;

    @Autowired
    SupplierWrapper supplierWrapper;

    @Autowired
    AppPushService appPushService;

    @Autowired
    JmsTemplate jmsTemplate;

    @Autowired
    SmsSendService smsSendService;

    @Autowired
    SmsWrapper smsWrapper;

    @Autowired
    RedisMQMessageSender messageSender;

    @Override
    public ApiResponse<Boolean> push(AppPushRequest pushRequest) {
        String userId = pushRequest.getUserId();
        String title = pushRequest.getTitle();
        String content = pushRequest.getContent();
        String action = pushRequest.getAction();
        Long vendorId = pushRequest.getVendorId();

        try {
            Assert.notNull(userId, "userId不能为空!");
            Assert.notNull(title, "title不能为空");
            Assert.notNull(content, "content不能为空!");
            Assert.notNull(action, "action不能为空!");
            Assert.notNull(vendorId, "vendorId不能为空!");

            //获取账号信息
            Supplier supplier = supplierWrapper.findSupplierWithCache(vendorId, MessageTypeEnum.APP_PUSH.getCode());
            AppPush appPush = new AppPush();
            appPush.setTarget(userId);
            appPush.setTitle(title);
            appPush.setContent(content);
            appPush.setAction(action);
            appPush.setVendorId(vendorId);
            appPush.setSupplierId(supplier.getId());
            appPush.setCreateTime(new Date());

            //保存数据库
            appPush.setStatus(0);
            boolean result = appPushService.insert(appPush);
//            Destination destination = new ActiveMQQueue(ConstantMQ.appPushMQ);
//            jmsTemplate.convertAndSend(destination, JSON.toJSONString(appPush));
            Long redisResult = messageSender.put(new Message(ConstantMQ.appPushMQ, JSON.toJSONString(appPush)));
            if(redisResult==null){
                smsWrapper.smsAlarmInfo(vendorId);
                PushResponse pushResponse = appPushService.pushing(vendorId,userId, title, content, action);
                if(pushResponse.getCode()==200){
                    appPush.setStatus(1);
                    boolean b = appPushService.updateById(appPush);
                    log.info("==>推送成功,参数:{},{},{},{}, 结果:{}", userId, title, content, action,b);
                    return ApiResponseBuilder.buildSuccess(true);
                }else{
                    appPush.setStatus(2);
                    appPush.setFailureCode(pushResponse.getCode()+"");
                    appPush.setFailureReason(pushResponse.getFailureReason());
                    boolean b = appPushService.updateById(appPush);
                    log.error("==>推送失败,参数:{},结果:{}", pushRequest,b);
                    return ApiResponseBuilder.buildError(MmsBaseResponseCode.SEND_PUSH_CODE_ERROR.code,MmsBaseResponseCode.SEND_PUSH_CODE_ERROR.msg);
                }
            }
            log.info("==>推送成功,参数:{},结果:{}", pushRequest,result);
            return ApiResponseBuilder.buildSuccess(true);
        }catch (MessageException me){
            log.error("推送失败：参数:{}, 结果:{}",pushRequest,me);
            return ApiResponseBuilder.buildError(ApiResponseCode.ERROR.getCode(),ApiResponseCode.ERROR.getMessage());
        }catch (Exception e){
            log.error("推送失败,参数:{},{},{},{},异常：{}", e);
            return ApiResponseBuilder.buildError(ApiResponseCode.ERROR.getCode(), e.getMessage(), false);
        }

    }

}
